//https://leetcode.cn/problems/implement-queue-using-stacks/

#define N 4

typedef int STDatatype;

typedef struct Stakc
{
	STDatatype* a;
	int top;
	int capacity;

}ST;


typedef struct {
	ST pushst;
	ST popst;

} MyQueue;

void STInit(ST* ps)
{
	assert(ps);

	ps->a = (STDatatype*)malloc(sizeof(STDatatype) * N);
	if (ps->a == NULL)
	{
		perror("malloc fail\n");
		return;
	}

	ps->capacity = N;
	ps->top = 0;  //表示栈顶的下一个元素

}

void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

void STPush(ST* ps, STDatatype x)
{
	assert(ps);

	if (ps->top == ps->capacity)
	{
		STDatatype* temp = (STDatatype*)realloc(ps->a, sizeof(STDatatype) * (ps->capacity) * 2);
		if (temp == NULL)
		{
			perror("realloc fail\n");
		}

		ps->a = temp;
		ps->capacity *= 2;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

bool STEmpty(ST* ps)
{
	return ps->top == 0;
}

void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->top--;

}

int STSize(ST* ps)
{
	assert(ps);

	return ps->top;
}

STDatatype STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	return ps->a[ps->top - 1];
}


MyQueue* myQueueCreate() {

	MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
	if (obj == NULL)
	{
		perror("malloc fail\n");
		return NULL;
	}

	STInit(&obj->pushst);
	STInit(&obj->popst);

	return obj;

}

void myQueuePush(MyQueue* obj, int x) {

	STPush(&obj->pushst, x);

}

int myQueuePeek(MyQueue* obj) {

	if (STEmpty(&obj->popst))
	{
		//倒数据
		while (!STEmpty(&obj->pushst))
		{
			STPush(&obj->popst, STTop(&obj->pushst));
			STPop(&obj->pushst);
		}
	}

	return STTop(&obj->popst);

}


int myQueuePop(MyQueue* obj) {

	int front = myQueuePeek(obj);
	STPop(&obj->popst);
	return front;


}

bool myQueueEmpty(MyQueue* obj) {

	return STEmpty(&obj->pushst) && STEmpty(&obj->popst);

}

void myQueueFree(MyQueue* obj) {

	STDestroy(&obj->pushst);
	STDestroy(&obj->popst);
	free(obj);

}
